package com.charlotte.clienterestmd5;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import java.io.*;
import java.util.Calendar;
import java.util.Locale;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main(String... parametros)
    {
        Locale local = new Locale("es","MX");
        System.out.printf("Comenzando a las = %1$td/%1$tm/%1$ty %1$tI:%1$tM:%1$tS %2$c",Calendar.getInstance(local),(char)10);
        if(parametros.length == 0)
            System.out.println("Debe especificar una palabra o frase a resumir.");
        else
        {
            Client cliente = new Client();
            cliente.setConnectTimeout(10000);
            ClientResponse response = null;
            try
            {
                response = cliente.resource("http://law-prueba-uno.appspot.com/sevice/One/").path("MD5").queryParam
                    ("password",parametros[0]).header("content-type","text/plain;charset=UTF-8").accept("text/html")
                    .get(ClientResponse.class);
                try(BufferedReader input = new BufferedReader(new InputStreamReader(response.getEntityInputStream())))
                {
                    File file = new Archivo(parametros.length >= 2 ? parametros[1] : System.getProperty("user.home")+"/hash.html");
                    try(BufferedWriter out = new BufferedWriter(new FileWriter(file)))
                    {
                        char[] buf = new char[50];
                        int tamBuf;
                        while((tamBuf = input.read(buf)) != -1)
                        {
                            out.write(buf,0,tamBuf);
                            out.flush();
                        }
                    }
                }
            }
            catch(UniformInterfaceException ui)
            {
                System.out.println(ui.getMessage());
                System.out.println(ui.getResponse() != null ? 
                "status = "+ui.getResponse().getStatus() : "Erro al conectarse al web service.");
            }
            catch(IOException io)
            {
                System.out.println(io.getMessage());
                System.out.println("Error con el archivo en donde se iba a guardar el resultado de la petición.");
            }
            finally
            {
                if(response != null)
                    response.close();
                cliente.destroy();
            }
        }
        System.out.printf("Terminando a las = %1$td/%1$tm/%1$ty %1$tI:%1$tM:%1$tS %2$c",Calendar.getInstance(local),(char)10);
    }
}
